/*
 * @Descripttion: 执行队列
 * @Version: 1.0
 * @Author: undead
 * @Date: 2021-04-08 11:11:12
 * @LastEditors: undead
 * @LastEditTime: 2021-05-10 11:34:57
 */

interface QueueItem {
    asyncFn: Function;
    /** 成功 */
    resolveFn: Function;
    /** 失败 */
    rejectFn: Function;
}

const operateQueue: QueueItem[] = [];
let lockStatus: boolean = false;

export default class Queue {
    static invokeQueue(fn: Function): Promise<any> {
        return new Promise((resolve, reject) => {
            operateQueue.push({
                asyncFn: fn,
                resolveFn: resolve,
                rejectFn: reject
            });
            queue.QueueRecursion();
        });
    }
    private async QueueRecursion(): Promise<void> {
        while (operateQueue.length >= 1 && !lockStatus) {
            lockStatus = true;
            const getOperation = operateQueue.shift();
            try {
                const result = await getOperation.asyncFn();
                getOperation.resolveFn(result);
            } catch (e) {
                getOperation.rejectFn(e);
            }
            lockStatus = false;
        }
    }
}
const queue = new Queue();
